package ants;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import cell.Cell;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;


/**
 * Static utility methods.
 */
public class Utils {
  
  public static Function<Collection<Integer>, Integer> extractSingletonFunction = new Function<Collection<Integer>, Integer>( ) {
                                                                                  
                                                                                  @Override
                                                                                  public Integer apply(Collection<Integer> set) {
                                                                                    return Iterators.getOnlyElement(set.iterator( ));
                                                                                  }
                                                                                  
                                                                                };
  
  
  public static <T> T firstNonNull(T arg1, T arg2) {
    return arg1 != null ? arg1 : arg2;
  }
  
  
  public static <T> ImmutableSet<T> setDifference(ImmutableList<T> list,
                                                  Set<T> set) {
    return ImmutableSet.copyOf(Sets.difference(ImmutableSet.copyOf(list), set));
  }
  
  
  public static <T> ImmutableList<T> shuffle(Iterable<T> arr) {
    final List<T> shuffled = new ArrayList<>( );
    for (final T e: arr)
      shuffled.add((int) (Math.random( ) * (shuffled.size( ) + 1)), e);
    return ImmutableList.copyOf(shuffled);
  }
  
  
  public static ImmutableList<Cell> take(int n, ImmutableList<Cell> list) {
    ImmutableList.Builder<Cell> listBuilder = ImmutableList.builder( );
    for (int i = 0; i < list.size( ) && i < n; i++)
      listBuilder.add(list.get(i));
    return listBuilder.build( );
  }
  
}
